package test.com.db.client;

import com.db.protocol.Command;
import com.db.protocol.Request;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoServer {
    public static void main(String... args) {
        try (ServerSocket ss = new ServerSocket(1234);
             Socket socket = ss.accept()) {
            try (ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
                 ObjectInputStream in = new ObjectInputStream(socket.getInputStream())) {

                Request request;
                int tryCounter = 1;
                do {
                    request = (Request)in.readObject();
                    switch (request.getCommand()) {
                        case chid:
                            if (tryCounter == 0) {
                                out.writeObject("nickname accepted");
                            } else {
                                --tryCounter;
                                out.writeObject("nickname already used");
                            }
                            break;
                        case hist:
                            out.writeObject("fig tebe a ne history");
                            break;
                        default:
                            out.writeObject(request.getArgument().toString());
                    }
                    System.err.println(request.getCommand().toString() + " " + request.getArgument());
                } while (request.getCommand() != Command.disconnect);
                System.err.println("test ok");
            }
        } catch (ClassNotFoundException | IOException e) {
            System.err.println("test end");
        }
    }
}
